package io.zhengsh.nio.charset;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;
import java.util.Map;

public class CharsetDemo {


    public static void main(String[] args) throws CharacterCodingException {

        // 1、获取 charset  对象
        Charset charset = Charset.forName("UTF-8");

        // 2、获得编码器对象
        CharsetEncoder charsetEncoder = charset.newEncoder();

        // 3、创建缓冲区
        CharBuffer charBuffer = CharBuffer.allocate(1025);
        charBuffer.put("hello 2020 ! 加油！");

        // 4、编码
        charBuffer.flip();
        ByteBuffer buffer = charsetEncoder.encode(charBuffer);
        System.out.println("编码后的字符：");
        for (int i = 0; i < buffer.limit(); i++) {
            System.out.println(buffer.get());
        }

        // 5、获取解码器对象
        buffer.flip();
        CharsetDecoder charsetDecoder = charset.newDecoder();


        // 6、解码
        CharBuffer charBuffer1 = charsetDecoder.decode(buffer);
        System.out.println("解码后的字符：");
        System.out.println(charBuffer1.toString());

        // 7、通过其他类型的解码器解码
        Charset charset1 = Charset.forName("GBK");
        CharsetDecoder charsetDecoder1 = charset1.newDecoder();
        CharBuffer charBuffer2 = charsetDecoder1.decode(buffer);
        System.out.println("解码后的字符(GBK)：");
        System.out.println(charBuffer2.toString());

        // 8、获取所有的字符串集
        Map<String, Charset> map = Charset.availableCharsets();
        map.forEach((k, v) -> System.out.println(k + "=" + v.toString()));
    }

}
